// 用户相关的小仓库
//@ts-nocheck
import { defineStore } from "pinia";
import {
  constantRoute,
  asyncRoutes,
  anyRoutes
} from '@/router/routes.js'
import cloneDeep from 'lodash/cloneDeep'
// 用于过滤当前用户需要展示的异步路由
function filterAsyncRoute(a, b) {
  return a.filter((item) => {
    if (b.includes(item.name)) {
      if (item.children && item.children.length > 0) {
        item.children = filterAsyncRoute(item.children, b)
      }
      return true;
    } else {
      return false;
    }
  });
}
export default defineStore("User", {
  // 小仓库储存数据的地方
  state: (): UserState => {
    return {
      token: '',
      sex: '',
      image: "",
      user: "",
      menuRoutes: constantRoute,
    };
  },

  // 异步逻辑的地方
  actions: {
    // 获取用户信息
    async userInfo() {
      let result: any = await reqUserInfo();
      if (result.code == 200) {
        this.username = result.data.name;
        this.avatar = result.data.avatar;
        // 获取用户异步路由
        let userAsyncRoute = filterAsyncRoute(cloneDeep(asyncRoutes), result.data.routes);
        // 菜单数据
        this.menuRoutes = [...constantRoute, ...userAsyncRoute, anyRoutes];
        // 动态添加路由
        [...userAsyncRoute, anyRoutes].forEach((route: any) => {
          router.addRoute(route);
        });
        return "ok";
      } else {
        return Promise.reject(new Error(result.message));
      }
    },
    logout() {
      this.$reset(); // 重置状态
    },
  },

  // 计算属性
  getters: {},
  // 持久化
  persist: {
    key: 'UserStore',// 自定义存储的键名
    storage: localStorage,// 可以改为sessionStorage
    enabled: true,
  }
});
